import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';

import '../../core/models/vote_model.dart';
import '../../core/providers/vote_provider.dart';
import '../../core/providers/user_provider.dart';
import '../../core/utils/popup_helper.dart';
import '../../core/utils/toast_helper.dart';

class VoteScreen extends ConsumerStatefulWidget {
  const VoteScreen({super.key});

  @override
  ConsumerState<VoteScreen> createState() => _VoteScreenState();
}

class _VoteScreenState extends ConsumerState<VoteScreen> {
  String? _selectedVoteId;
  bool _hasVoted = false;

  @override
  void initState() {
    super.initState();
    _checkUserVoteStatus();
  }

  void _checkUserVoteStatus() {
    final currentUser = ref.read(currentUserProvider);
    if (currentUser != null) {
      final userCurrentVote = ref.read(userCurrentVoteProvider(currentUser.id));
      if (userCurrentVote != null) {
        setState(() {
          _selectedVoteId = userCurrentVote.voteId;
          _hasVoted = true;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/resources/common_bg_2.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          bottom: false,
          child: Stack(
            children: [
              [
                _buildTopNavigationBar(),
                SizedBox(height: 20.h),
                _buildHeaderSection(),
                SizedBox(height: 24.h),
                _buildVoteList().expanded(),
              ].toColumn(),
              _buildKidImage(),
            ],
          ),
        ),
      ),
      floatingActionButton: _buildVoteButton(),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
    );
  }

  Widget _buildTopNavigationBar() {
    return [
      Container(
        width: 30.w,
        height: 30.w,
        decoration: BoxDecoration(color: Colors.black, shape: BoxShape.circle),
        child:
            Icon(
              Icons.arrow_back_ios_new,
            ).iconSize(20.sp).iconColor(Colors.white).center(),
      ).inkWell(onTap: () => GoRouter.of(context).pop()),
      Expanded(
        child: Text(
          'Initiate a game vote',
          textAlign: TextAlign.center,
          style: TextStyle(
            fontSize: 24.sp,
            fontWeight: FontWeight.bold,
            color: Colors.black,
            fontFamily: 'PoetsenOne',
          ),
        ),
      ),
      SizedBox(width: 36.w),
    ].toRow().padding(horizontal: 16.w, vertical: 20.h);
  }

  Widget _buildHeaderSection() {
    return Container(
      padding: EdgeInsets.only(left: 100.w),
      child: SizedBox(
        height: 83.h,
        child: AspectRatio(
          aspectRatio: 235.5 / 83,
          child: Image.asset(
            'assets/resources/vote_title.png',
            fit: BoxFit.fill,
          ),
        ),
      ),
    );
  }

  Widget _buildKidImage() {
    return Positioned(
      left: 0.w,
      top: 40.h,
      child: Image.asset(
        'assets/resources/kid.png',
        width: 149.w,
        height: 199.w,
        fit: BoxFit.contain,
      ),
    );
  }

  Widget _buildVoteList() {
    final votes = ref.watch(voteProvider);

    return Container(
      decoration: BoxDecoration(
        color: Color(0xFFFDF5E1),
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(20.r),
          topRight: Radius.circular(20.r),
        ),
      ),
      padding: EdgeInsets.only(top: 3.h),
      child: Container(
        decoration: BoxDecoration(
          color: Color(0xFF2AB061),
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(18.r),
            topRight: Radius.circular(18.r),
          ),
        ),
        child: Column(
          children: [
            SizedBox(height: 10.h),
            Expanded(
              child: ListView.builder(
                padding: EdgeInsets.only(left: 16.w, right: 16.w, bottom: 90.h),
                itemCount: votes.length,
                itemBuilder: (context, index) {
                  final vote = votes[index];
                  final isSelected = _selectedVoteId == vote.voteId;
                  return _buildVoteItem(vote, index + 1, isSelected);
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildVoteItem(VoteEntity vote, int index, bool isSelected) {
    return Container(
      margin: EdgeInsets.only(bottom: 16.h),
      child:
          [
            _buildVoteContentBox(vote, index, isSelected).expanded(),
            SizedBox(width: 12.w),
            _buildVoteStatusBox(vote, isSelected),
          ].toRow(),
    ).inkWell(onTap: _hasVoted ? null : () => _selectVote(vote.voteId));
  }

  Widget _buildIndexBox(int index) {
    return Transform.rotate(
      angle: -0.1,
      child: Container(
        width: 49.w,
        height: 49.w,
        decoration: BoxDecoration(
          color: Color(0xFFA4E633),
          borderRadius: BorderRadius.circular(8.r),
        ),
        child:
            Text(
              '$index',
              style: TextStyle(
                fontSize: 36.sp,
                fontWeight: FontWeight.bold,
                color: Colors.black,
                fontFamily: 'PoetsenOne',
              ),
            ).center(),
      ),
    );
  }

  Widget _buildVoteContentBox(VoteEntity vote, int index, bool isSelected) {
    final backgroundImage =
        isSelected
            ? 'assets/resources/vote_card_selected.png'
            : 'assets/resources/vote_card_common.png';

    return SizedBox(
      height: 93.h,
      child: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(backgroundImage),
            fit: BoxFit.fill,
          ),
        ),
        child:
            [
              SizedBox(width: 12.w),
              _buildIndexBox(index),
              Expanded(
                child: Container(
                  padding: EdgeInsets.symmetric(
                    horizontal: 16.w,
                    vertical: 12.h,
                  ),
                  child:
                      Text(
                        vote.description,
                        style: TextStyle(
                          fontSize: 13.sp,
                          fontWeight: FontWeight.w600,
                          color: Colors.black,
                        ),
                        maxLines: 3,
                        overflow: TextOverflow.ellipsis,
                      ).center(),
                ),
              ),
            ].toRow(),
      ),
    );
  }

  Widget _buildVoteStatusBox(VoteEntity vote, bool isSelected) {
    String backgroundImage;
    Widget content;

    if (_hasVoted) {
      backgroundImage = 'assets/resources/vote_card_bg.png';
      content =
          [
                Text(
                  '${vote.voteCount}',
                  style: TextStyle(
                    fontSize: 16.sp,
                    fontWeight: FontWeight.bold,
                    color: Colors.black,
                    fontFamily: 'PoetsenOne',
                  ),
                ),
                Text(
                  'votes',
                  style: TextStyle(
                    fontSize: 16.sp,
                    fontWeight: FontWeight.w500,
                    color: Colors.black,
                    fontFamily: 'PoetsenOne',
                  ),
                ),
              ]
              .toColumn(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
              )
              .center();
    } else {
      backgroundImage =
          isSelected
              ? 'assets/resources/vote_selected.png'
              : 'assets/resources/vote_common.png';
      content = SizedBox.shrink();
    }

    return SizedBox(
      width: 66.w,
      height: 92.h,
      child: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(backgroundImage),
            fit: BoxFit.fill,
          ),
        ),
        child: content,
      ),
    );
  }

  Widget _buildVoteButton() {
    if (_hasVoted) return SizedBox.shrink();

    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: Container(
        height: 56.h,
        width: double.infinity,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/resources/vote_button.png'),
            fit: BoxFit.fill,
          ),
        ),
      ).inkWell(onTap: _selectedVoteId != null ? _submitVote : null),
    );
  }

  void _selectVote(String voteId) {
    if (_hasVoted) return;

    setState(() {
      _selectedVoteId = voteId;
    });
  }

  Future<void> _submitVote() async {
    if (_selectedVoteId == null || _hasVoted) return;

    final currentUser = ref.read(currentUserProvider);
    if (currentUser == null) {
      PopupHelper.showLoginDialog(
        context,
        onLoginPressed: () {
          GoRouter.of(context).push('/login');
        },
        onCancelPressed: () {},
      );
      return;
    }

    try {
      final voteNotifier = ref.read(voteProvider.notifier);
      final success = await voteNotifier.vote(_selectedVoteId!, currentUser.id);

      if (mounted) {
        if (success) {
          setState(() {
            _hasVoted = true;
          });
          ToastHelper.success('Vote submitted successfully!', context: context);
        } else {
          ToastHelper.error('Failed to submit vote', context: context);
        }
      }
    } catch (e) {
      if (mounted) {
        ToastHelper.error('Failed to submit vote', context: context);
      }
    }
  }
}
